package com.fulihui.wgj.board.websocket.application;

import com.fulihui.wgj.board.websocket.message.LoggerMessage;
import com.fulihui.wgj.board.websocket.queue.LoggerQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: Levon
 * @date: 2018-07-12 16:47
 */
@Component
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketLoggerApp {

    private Logger logger = LoggerFactory.getLogger(WebSocketLoggerApp.class);

    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    int info = 1;

    @Scheduled(fixedRate = 1000)
    public void outputLogger() {
        logger.info("啦啦啦啦，输出日志：" + info++);
    }

    @PostConstruct
    public void pushLogger() {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        Runnable runnable = () -> {
            while (true) {
                try {
                    LoggerMessage log = LoggerQueue.getInstance().poll();
                    if (log != null) {
                        if (messagingTemplate != null) {
                            messagingTemplate.convertAndSend("/topic/pullLogger", log);
                            messagingTemplate.convertAndSend("/topic/logtotal", info);

                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        executorService.submit(runnable);
    }

}
